﻿using UnityEngine;
using System.Collections;

namespace DoomWad
{
	public class MapSide : MapObject
	{
		public MapWall wall;

		public MapFlat upperFlat;
		public int upperVertexIndex1 = -1;
		public int upperVertexIndex2 = -1;

		public MapFlat lowerFlat;
		public int lowerVertexIndex1 = -1;
		public int lowerVertexIndex2 = -1;

		/// <summary>
		/// Если true, то текстура "закреплена" на верхнем флате, если false - то на нижнем
		/// </summary>
		public bool pegToBottom = false;

		protected new void Awake()
		{
			base.Awake();
		}

		// Update is called once per frame
		protected new void Update()
		{
			base.Update();
		}

		public void UpdateMesh()
		{
			Vector3[] vertices = new Vector3[ 4 ];

			vertices[ 0 ] = transform.worldToLocalMatrix.MultiplyPoint( lowerFlat.GetWorldVertex( lowerVertexIndex1 ) );
			vertices[ 1 ] = transform.worldToLocalMatrix.MultiplyPoint( lowerFlat.GetWorldVertex( lowerVertexIndex2 ) );
			vertices[ 2 ] = transform.worldToLocalMatrix.MultiplyPoint( upperFlat.GetWorldVertex( upperVertexIndex1 ) );
			vertices[ 3 ] = transform.worldToLocalMatrix.MultiplyPoint( upperFlat.GetWorldVertex( upperVertexIndex2 ) );

			mesh.vertices = vertices;

			mesh.RecalculateNormals();
			mesh.RecalculateBounds();

			//----------------------------------------------------------------------------------
			// Texture UV
			//----------------------------------------------------------------------------------

			Vector2[] uv = new Vector2[ 4 ];

			float u_scale = ( float ) WadDefs.PIXELS_PER_UNIT / ( float ) mat.mainTexture.width;
			float v_scale = ( float ) WadDefs.PIXELS_PER_UNIT / ( float ) mat.mainTexture.height;

			float u_width = ( vertices[ 1 ] - vertices[ 0 ] ).magnitude * u_scale;
			float v_height = ( vertices[ 2 ] - vertices[ 0 ] ).magnitude * v_scale;

			Rect uvRect = new Rect();
			uvRect.xMin = 0f;
			uvRect.xMax = u_width;
			if ( pegToBottom )
			{
				uvRect.yMin = 0f;
				uvRect.yMax = v_height;
			}
			else
			{
				uvRect.yMin = 1f - v_height;
				uvRect.yMax = 1f;
			}

			uv[ 0 ] = new Vector2( uvRect.xMin, uvRect.yMin );
			uv[ 1 ] = new Vector2( uvRect.xMax, uvRect.yMin );
			uv[ 2 ] = new Vector2( uvRect.xMin, uvRect.yMax );
			uv[ 3 ] = new Vector2( uvRect.xMax, uvRect.yMax );

			mesh.uv = uv;
		}

		//void OnDrawGizmos()
		//{
		//	if ( UnityEditor.Selection.Contains( gameObject ) )
		//	{
		//		Gizmos.matrix = Matrix4x4.identity;

		//		Gizmos.color = Color.green;
		//		Gizmos.DrawWireCube( upperFlat.GetWorldVertex( upperVertexIndex1 ), Vector3.one * 0.25f );
		//		Gizmos.DrawWireCube( upperFlat.GetWorldVertex( upperVertexIndex2 ), Vector3.one * 0.25f );

		//		Gizmos.color = Color.red;
		//		Gizmos.DrawWireCube( lowerFlat.GetWorldVertex( lowerVertexIndex1 ), Vector3.one * 0.25f );
		//		Gizmos.DrawWireCube( lowerFlat.GetWorldVertex( lowerVertexIndex2 ), Vector3.one * 0.25f );
		//	}
		//}
	}
}